<?php 
namespace app\sched\controller;

use think\Controller;
use app\common\model\trade\TradeLeveraged;
use app\common\controller\Marcketline;
use app\common\model\coin\CoinUser;
use think\Db;
use app\common\model\user\Users;
use app\common\model\user\UserActParam;
use app\common\controller\Finance;

class Trade extends Controller
{
	public function tradeLeveleraged()
	{
		$this->tradeBuy();
		$this->tradeSale();
	}
	/**
	 * 杠杆交易买入
	 */
	public function tradeBuy()
	{
		$buy_list = TradeLeveraged::where(['state' => 1,'trade_style' => 1])->select();
		$line = $this->getNowLine();
		$res = [];
		$trade_id = [];
		$act = [];
		foreach ($buy_list as $rows) {
			$item_line = $line[$rows['symbol']];
			//当前盈亏额度
			$rate = $rows['symbol'] == 'btcusdt' ? 100 / $rows['multi'] : 10 / $rows['multi'];
			$loss = $rows['capital'] * ($item_line['close'] - $rows['buy_price'] ) / $rate;
			//订单止盈
			$loss_up = $rows['loss_up'] * $rows['capital'] / 100;
			//订单止损
			//$rows['loss_down'] = $rows['loss_down'] == 80 ? 100 : $rows['loss_down'];
			$loss_down = $rows['loss_down'] * $rows['capital'] / 100;
			//到达止盈额度
			$dec_num = $rows['capital'] + $rows['fee'];
			if($loss >= $loss_up) {
				//获取用户信息
				$user_lock = Users::where(['id' => $rows['user_id']])->value('is_lock');
				if($user_lock)continue;
				//给用户平仓
				$real_num = $rows['capital'] + $loss_up;
				$temp = [
						'user_id' => $rows['user_id'],
						'coin_id' => $rows['quote_currency'],
						'avalible_price' => Db::raw("avalible_price + {$real_num}"),
						'freezing_price' => Db::raw("freezing_price - {$dec_num}"),
				];
				$res[] = $temp;
				$trade_id[] = [
						'id' => $rows['id'],
						'state' => 0,
						'update_time' => time(),
						'real_price' => $loss_up,
						'close' =>$item_line['close'] 
				];
				$act[] = [
						'user_id' => $rows['user_id'],
						'fee' => $rows['fee'],
						'price' => -$loss_up
				];
			}
			//达到止损
			if(-$loss >= $loss_down) {
				if($rows['loss_down'] == 80) $loss_down = 100 * $rows['capital'] / 100;
				$real_num = $rows['capital'] - $loss_down;
				$temp = [
						'user_id' => $rows['user_id'],
						'coin_id' => $rows['quote_currency'],
						'avalible_price' => Db::raw("avalible_price + {$real_num}"),
						'freezing_price' => Db::raw("freezing_price - {$dec_num}"),
				];
				$dec_num = $rows['capital'];
				$res[] = $temp;
				$trade_id[] = [
						'id' => $rows['id'],
						'state' => 0,
						'update_time' => time(),
						'real_price' => $loss_down,
						'close' =>$item_line['close'] 
				];
				$act[] = [
						'user_id' => $rows['user_id'],
						'fee' => $rows['fee'],
						'price' => $loss_down
				];
				
			}
		} 
		$coin_user = new CoinUser();
		foreach ($res as $val) {
			CoinUser::where(['user_id' => $val['user_id'],'coin_id' => $val['coin_id']])->update($val);
		}
		$trade = new TradeLeveraged();
		$trade -> isUpdate() ->saveAll($trade_id);
		$this->actBounce($act);
// 		$coin_user->isUpdate()->saveAll($res);
// 		TradeLeveraged::where(['id' => ['in',$trade_id]])->update(['state' => 0]);
	}
	
	/**
	 * 交易
	 */
	public function tradeSale()
	{
		$buy_list = TradeLeveraged::where(['state' => 1,'trade_style' => 2])->select();
		$line = $this->getNowLine();
		$res = [];
		$trade_id = [];
		$act = [];
		foreach ($buy_list as $rows) {
			$item_line = $line[$rows['symbol']];
			//当前盈亏额度
			$rate = $rows['symbol'] == 'btcusdt' ? 100 / $rows['multi'] : 10 / $rows['multi'];
			$loss = $rows['capital'] * ($item_line['close'] - $rows['buy_price'] ) / $rate;
			//订单止盈
			$loss_up = $rows['loss_up'] * $rows['capital'] / 100;
			//订单止损
			$rows['loss_down'] = $rows['loss_down'] == 80 ? 100 : $rows['loss_down'];
			$loss_down = $rows['loss_down'] * $rows['capital'] / 100;
			$dec_num = $rows['capital'] + $rows['fee'];
			//到达止盈额度
			if(-$loss >= $loss_up) {
				//获取用户信息
				$user_lock = Users::where(['id' => $rows['user_id']])->value('is_lock');
				if($user_lock)continue;
				//给用户平仓
				$real_num = $rows['capital'] + $loss_up;
				$temp = [
						'user_id' => $rows['user_id'],
						'coin_id' => $rows['quote_currency'],
						'avalible_price' => Db::raw("avalible_price + {$real_num}"),
						'freezing_price' => Db::raw("freezing_price - {$dec_num}"),
						];
				$res[] = $temp;
				$trade_id[] = [
						'id' => $rows['id'],
						'state' => 0,
						'update_time' => time(),
						'real_price' => $loss_up,
						'close' =>$item_line['close'] 
				];
				$act[] = [
						'user_id' => $rows['user_id'],
						'fee' => $rows['fee'],
						'price' => -$loss_up
				];
			}
			//达到止损
			if($loss >= $loss_down) {
				if($rows['loss_down'] == 80) $loss_down = 100 * $rows['capital'] / 100;
				$real_num = $rows['capital'] - $loss_down;
				//给用户平仓
				$temp = [
						'user_id' => $rows['user_id'],
						'coin_id' => $rows['quote_currency'],
						'avalible_price' => Db::raw("avalible_price + {$real_num}"),
						'freezing_price' => Db::raw("freezing_price - {$dec_num}"),
						];
				$res[] = $temp;
				$trade_id[] = [
						'id' => $rows['id'],
						'state' => 0,
						'update_time' => time(),
						'real_price' => $loss_down,
						'close' =>$item_line['close'] 
				];
				$act[] = [
						'user_id' => $rows['user_id'],
						'fee' => $rows['fee'],
						'price' => $loss_down
				];
			}
		} 
		$coin_user = new CoinUser();
		foreach ($res as $val) {
			CoinUser::where(['user_id' => $val['user_id'],'coin_id' => $val['coin_id']])->update($val);
		}
		$trade = new TradeLeveraged();
		$trade -> isUpdate() ->saveAll($trade_id);
		$this->actBounce($act);
	}
	/**
	 * 获取实时价格
	 * @return unknown
	 */
	public function getNowLine()
	{
		$marcke = new Marcketline();
		$btcusdt = $marcke->getSymbolClose('btcusdt');
		$bchusdt = $marcke->getSymbolClose('bchusdt');
		$ethusdt = $marcke->getSymbolClose('ethusdt');
		$res = [
				'btcusdt' => $btcusdt,
				'bchusdt' => $bchusdt,
				'ethusdt' => $ethusdt
		];
		return $res;
	}
	
	public function actBounce($act)
	{
		foreach ($act as $rows) {
			$this->setActFinance($rows);
		}
	}
	
	public function getActParam($user_id)
	{
		$param = UserActParam::where(['user_id' => $user_id])->find();
		if(!$param) {
			$param = UserActParam::where(['id' => 1])->find();
		}
		return $param;
	}
	
	public function setActFinance($data)
	{
		$finance = new Finance();
		//获取代理ID
		$act_id = Users::where(['id' => $data['user_id']])->value('act_id');
		if($act_id) {
			//获取代理
			$act = Users::get($act_id);
			if($data['price'] > 0){
				Users::where(['id' => $act_id])->setInc('bail',$data['price']);
				$finance->addActFinance($act_id, $data['user_id'], $data['price'], '保证金收益'.$data['price'], 2);
			} else {
				//$res_price = $act->bail + $data['price'] > 0 ? -$data['price'] : -$data['price'] - $act->bail;
				$res_price = -$data['price'];
				Users::where(['id' => $act_id])->setDec('bail',$res_price);
				$finance->addActFinance($act_id, $data['user_id'], -$res_price, '保证金扣除'.$res_price, 2);
			}
			
		}
		
	}

}